/*
 * $Id: sem.c,v 1.1 2006-06-03 15:56:31 bacon Exp $
 */

#include <xp/bas/thr.h>
#include <xp/bas/sem.h>
#include <xp/bas/time.h>
#include <xp/bas/stdio.h>

xp_sem_t sem;

int dummy (xp_thr_t* thr)
{
	int i;

	if (xp_sem_acquire (&sem) == -1) 
		xp_printf (XP_T("cannot acquire semaphore\n"));

	for (i = 0; i < 5; i++) {
		xp_printf (XP_T("dummy. %i\n"), i);
		xp_sleep (1000);
	}

	if (xp_sem_release (&sem) == -1) 
		xp_printf (XP_T("cannot release semaphore\n"));

	return 0;
}

int xp_main ()
{
	xp_thr_t thr1, thr2, thr3;

	if (xp_thr_open (&thr1, dummy, 0) == XP_NULL) {
		xp_printf (XP_T("cannot open thread\n"));
		return -1;
	}
	if (xp_thr_open (&thr2, dummy, 0) == XP_NULL) {
		xp_printf (XP_T("cannot open thread\n"));
		return -1;
	}
	if (xp_thr_open (&thr3, dummy, 0) == XP_NULL) {
		xp_printf (XP_T("cannot open thread\n"));
		return -1;
	}

	if (xp_sem_open (&sem, 2) == XP_NULL) {
		xp_printf (XP_T("cannot create a semaphore\n"));
		return -1;
	}

	if (xp_thr_start (&thr1, 0) == -1) {
		xp_printf (XP_T("cannot start thread\n"));
		return -1;
	}
	if (xp_thr_start (&thr2, 0) == -1) {
		xp_printf (XP_T("cannot start thread\n"));
		return -1;
	}
	if (xp_thr_start (&thr3, 0) == -1) {
		xp_printf (XP_T("cannot start thread\n"));
		return -1;
	}

	xp_thr_join (&thr1);
	xp_thr_join (&thr2);
	xp_thr_join (&thr3);

	xp_sem_close (&sem);

	xp_thr_close (&thr1);
	xp_thr_close (&thr2);
	xp_thr_close (&thr3);

	return 0;
}
